package com.suncky.example.http.coroutines

import com.google.gson.JsonParseException
import com.suncky.example.http.DataPage
import com.suncky.example.http.HttpErrorResult
import com.suncky.frame.http.bean.ErrorResult
import com.suncky.frame.http.coroutines.KRequest
import com.suncky.frame.http.coroutines.KError
import com.suncky.frame.utils.GsonUtils
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.text.ParseException
import javax.net.ssl.SSLHandshakeException

class KHttpRequest<E> : KRequest<E, DataPage, KHttpResult<E>,HttpErrorResult>(){

    @Suppress("UNCHECKED_CAST")
    companion object{
        fun <E> get(): KHttpRequest<E> = InstanceHolder.holder as KHttpRequest<E>
    }
    private object InstanceHolder {
        val holder= KHttpRequest<Any>()
    }

     override fun onHandleError(code: Int?, message: String?): Boolean {
        return false
    }

    override fun onCreateExceptionResult(e: Exception,errorResult: HttpErrorResult?): KHttpResult<E> {
        return when (e) {
            is HttpException -> KHttpResult.error(KError.HTTP_STATUS_ERROR, e)
            is ConnectException -> KHttpResult.error(KError.CONNECT_FAIL, e)
            is SocketTimeoutException -> KHttpResult.error(KError.SOCKET_TIMEOUT, e)
            is UnknownHostException -> KHttpResult.error(KError.UNKNOWN_HOST, e)
            is JsonParseException,
            is JSONException,
            is ParseException -> KHttpResult.error(KError.JSON_ERROR, e)
            is SSLHandshakeException -> KHttpResult.error(KError.SSL_HANDSHAKE, e)
            else -> return KHttpResult.error(KError.UNKNOWN_ERROR, e)
        }
    }



    override fun onGetErrorResult(e: Exception): HttpErrorResult? {
        if (e is HttpException && e.code() == 500) {
            return GsonUtils.jsonToObject(HttpErrorResult::class.java, e.response()?.errorBody()?.string())
        }
        return null
    }

    override fun  onHandleException(e: Exception, errorResult: HttpErrorResult?): Boolean {
        return false
    }

}